package lion.framework.core.web.path;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

/**
 * 路径映射，映身有两种，直接路径和参数化路径，直接路径通过Map直接获取，参数化路径则从RootNode节点开始查找
 *
 * <pre>
 * time   2013 2013-4-24 上午11:32:04
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
public class PathNodeMapping {

	public static PathNode rootPatternNode = new PathNode("");
	public static Map<String, PathNode> pathNodeMapping = new HashMap<>();

	public static PathNode add(String path) {

		if (StringUtils.isBlank(path)) { return null; }
		path = path.replaceAll("/{2,}", "/").replaceAll("^/|/$", "");

		PathNode node = find(path);
		if (node != null) { return node; }
		if (ParameterizedPath.isParameteredPath(path)) {
			node = rootPatternNode.add(path);
		} else {
			node = new PathNode(path);
			pathNodeMapping.put(path.toLowerCase(), node);
		}

		return node;
	}

	public static PathNode getRootPathNode() {

		return rootPatternNode;
	}

	public static PathNode find(String path) {

		if (StringUtils.isBlank(path)) { return null; }

		path = path.replaceAll("/{2,}", "/").replaceAll("^/|/$", "");

		PathNode node = pathNodeMapping.get(path.toLowerCase());
		if (node == null) {
			node = rootPatternNode.find(path);
		}
		return node;
	}
}
